var material_model = null;
var information_type = null;
var voltage_type = null;
var buy_type = null;
var modelGuid = GetUrlParam("modelGuid");
var bigtype = GetUrlParam("mBigtype");
var Y = GetUrlParam("Y");
var delId = GetUrlParam("delId");
$(function () {
    if(Y=="y"){
        $("#mBigtype").attr("disabled","disabled");
        $("#name").attr("disabled","disabled");
    }
    $.when(
    	getdatadictionary("material_model"),
        getdatadictionary("information_type"),
    	getdatadictionary("voltage_type"),
    	getdatadictionary("buy_type"),
        getBigtype()
    ).done(
    $("#jqGrid").jqGrid({
        url: baseURL + 'api/bmaterial/list?mBigtype='+bigtype,
        datatype: "json",
        colModel: [
            {label: 'guid', name: 'guid', index: 'guid', width: 50, key: true, hidden: true},
            {   hidden: true,
                label: '信息库类别',
                name: 'mInformationType',
                index: 'm_information_type',
                width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in information_type) {
                        if (cellvalue == information_type[d].dKey) return information_type[d].dValue;
                    }
                }
            },
            {label: '物质编码', name: 'mCode', index: 'm_code', width: 80,hidden: true},
            {label: '材料大类', name: 'mBigtype', index: 'm_bigtype', width: 120},
            {label: '材料中类', name: 'mMidtype', index: 'm_midtype', width: 120},
            {label: '材料类型', name: 'mLabel', index: 'm_label', width: 120},
            {label: '材料名称', name: 'mName', index: 'm_name', width: 200},
            {label: '技术参数', name: 'mParameter', index: 'm_parameter', width: 80},
            {hidden: true,
                label: '电压等级', name: 'mVoltage', index: 'm_voltage', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in voltage_type) {
                        if (cellvalue == voltage_type[d].dKey)
                            return voltage_type[d].dValue;
                    }
                    return "";
                }
            },
            {label: '参数', name: 'mBParameter', index: 'm_b_parameter', width: 120,hidden: true},
            {label: '预算值', name: 'mQuery', index: 'm_query', width: 80,hidden: true},
            {hidden: true,
                label: '采购级别', name: 'mBuyType', index: 'm_buy_type', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in buy_type) {
                        if (cellvalue == buy_type[d].dKey) return buy_type[d].dValue;
                    }
                }
            },
            {label: '购置单位', name: 'mUnit', index: 'm_unit', width: 80,hidden: true},
            {label: '购置单价', name: 'mPrice', index: 'm_price', width: 80,hidden: true},
            {hidden: true,label: '单重（kg）', name: 'mWeight', index: 'm_weight', width: 80},
            {label: '是否主材', name: 'mIsmain', index: 'm_ismain', width: 80,hidden: true},
            {label: '配置预算项', name: 'mIshave', index: 'm_ishave', width: 80,hidden: true},
            {label: '预算项目分类', name: 'mClass', index: 'm_class', width: 80,hidden: true},
            {label: '预算项目', name: 'mItem', index: 'm_item', width: 80,hidden: true}
        ],
        viewrecords: true,
        height: "100%",
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    })
	)
});


//  添加数量至中间页面
function saveMaterialToMid() {
    del(delId);
    var url = "bss/dmaterialmodelitem/saveMaterial";
    //  获取所选行id
    var ids = $("#jqGrid").jqGrid('getGridParam', 'selarrrow');
    if(ids.length > 0){
        for(var i=0;i<ids.length;i++){
            var rowData = $("#jqGrid").jqGrid('getRowData', ids[i]);    //  获取所选行数据
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify({
                    "modelGuid":modelGuid ,
                    "materialGuid":rowData.guid	,
                    "count":1
                }),
                success: function(r){
                    if(r.code === 0){
                        alert(r.msg, function(index){
                            parent.location.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        }
    }
}


function del(guid) {
    var arr = new Array();
    arr.push(guid)
    $.ajax({
        type: "POST",
        url: baseURL + "bss/dmaterialmodelitem/delete",
        contentType: "application/json",
        data: JSON.stringify(arr),
        success: function(r){
            if(r.code == 0){
                // alert('操作成功', function(index){
                //     $("#jqGrid").trigger("reloadGrid");
                // });
            }else{
                alert(r.msg);
            }
        }
    });
}


//  获取大类
function getBigtype() {
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getBigtype",
        success:function(data){
            for(var i=0;i<data.bigtype.length;i++){
                var sel = document.getElementById('mBigtype');
                sel.options.add(new Option(""+data.bigtype[i].mBigtype+"",""+data.bigtype[i].mBigtype+""));
            }
        }
    });
}

//  大类被选中后触发事件查询对应大类下的中类
function chooseBigtype() {

    var mt = $("#mBigtype").val();
    var sel = document.getElementById('mMidtype');
    sel.options.length=0;
    if(mt==""){
        mt = bigtype;
    }
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getMidtype?mBigtype="+mt,
        success:function(data){
            for(var i=0;i<data.midtype.length;i++){
                sel.options.add(new Option(""+data.midtype[i].mMidtype+"",""+data.midtype[i].mMidtype+""));
            }
        }
    });
}



//	字典
function getdatadictionary(sss)
{
    $.get(baseURL + "api/bdatadictionary/select?d_code="+sss, function(r){
        if(sss=="material_model"){
            material_model=r.returnlist;
        }else if (sss == "information_type") {
            information_type = r.returnlist;
        } else if (sss == "voltage_type") {
            voltage_type = r.returnlist;
        } else if (sss == "buy_type") {
            buy_type = r.returnlist;
        }
        vm.material_model=material_model;
        vm.information_type=information_type;
        vm.voltage_type=voltage_type;
        vm.buy_type=buy_type;
    });
}


var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        q:{
            mtype:null,
            name:null,
            Btype:null,
            mMidtype:null
        },
		dMaterialModel: {},
        material_model:material_model
        // gbp:gbp
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dMaterialModel = {};
		},
		update: function (event) {
			var guid = getSelectedRow();
			if(guid == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            vm.getInfo(guid)
		},
		saveOrUpdate: function (event) {
			var url = vm.dMaterialModel.guid == null ? "bss/dmaterialmodel/save" : "bss/dmaterialmodel/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.dMaterialModel),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var guids = getSelectedRows();
			if(guids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "bss/dmaterialmodel/delete",
                    contentType: "application/json",
				    data: JSON.stringify(guids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(guid){
			$.get(baseURL + "bss/dmaterialmodel/info/"+guid, function(r){
                vm.dMaterialModel = r.dMaterialModel;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'mtype': vm.q.mtype,
                    'mName': vm.q.name,
                    'mBigtype':$("#mBigtype").val(),
                    'mMidtype':$("#mMidtype").val()
                },
                page:page
            }).trigger("reloadGrid");
		}
	}
});